/**
 * @author xhw
 */

public class 死锁 {
    //给两个资源
    private static final Object resource1 = new Object();
    private static final Object resource2 = new Object();

    public static void main(String[] args) {
        // 创建第一个线程，尝试先锁定resource1然后锁定resource2
        Thread thread1 = new Thread(() -> {
            synchronized (resource1) {
                System.out.println("线程1锁定了resource1");
                System.out.println("线程1想要锁定resource2");
                synchronized (resource2) {
                    System.out.println("线程1锁定了resource2");
                }
            }
        });

        // 创建第二个线程，尝试先锁定resource2然后锁定resource1
        Thread thread2 = new Thread(() -> {
            synchronized (resource2) {
                System.out.println("线程2锁定了resource2");
                System.out.println("线程2试图锁定resource1");
                synchronized (resource1) {
                    System.out.println("线程2锁定了resource1");
                }
            }
        });

        // 启动两个线程
        thread1.start();
        thread2.start();
    }
}
